Exercises
Supercharged Button
Alright, let's get some practice forwarding refs along!
In the sandbox below, we have a <Button>
component, and we want to set it up to be a “supercharged” button. This means that we should be able to capture a reference to it, as well as forward all props along to it.
Acceptance Criteria:
- When hovering or focusing the button in the DOM, it should log "Captured ref: HTMLElement" in the console.
- There should be no console warnings.
Code Playground
import React from 'react';
import Button from './Button';
function App() {
const buttonRef = React.useRef();
function logRef() {
console.log('Captured ref:', buttonRef.current);
}
return (
<Button
ref={buttonRef}
onMouseEnter={logRef}
onFocus={logRef}
>
Hover or Focus Me
</Button>
);
}
export default App;
preview
console
- Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Check the render method of `App`. at Button (https://sandpack-bundler.vercel.app/Button.js:19:3) at App (https://sandpack-bundler.vercel.app/App.js:22:36)
Solution:
SquareSlider forwarding
One of the great things about React is the ability to “compose” components. For example, we can build a SquareSlider
component that builds on the lower-level Slider
component, locking in specific values.
In the sandbox below, we're trying to capture a ref on a <SquareSlider>
component, but it isn't working. Your job is to fix it.
Acceptance Criteria:
- The
sliderRef
ref should hold a reference to the<input type="range">
. - You can verify this in the console. It should show that
sliderRef
holds anHTMLElement
.
Code Playground
import React from 'react';
import SquareSlider from './SquareSlider';
function App() {
const sliderRef = React.useRef();
React.useEffect(() => {
// Log the value on mount
console.log(sliderRef.current);
}, []);
return (
<main>
<SquareSlider
ref={sliderRef}
label="Intensity"
min={0}
max={10}
/>
</main>
);
}
export default App;
preview
console
- Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? Check the render method of `App`. at SquareSlider at main at App (https://sandpack-bundler.vercel.app/App.js:22:36)
undefined
undefined
Solution: